package com.hutianao.gqgl.spring.tag;

import com.hutianao.gqgl.spring.tag.entity.DictTagEntity;
import com.hutianao.gqgl.spring.tag.service.DicDataTagService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.List;

public class DicDataProcessor extends AbstractAttributeTagProcessor {
    private static final String TEXT_ATTRIBUTE  = "dicselect";
    private static final int PRECEDENCE = 10000;
    private static final String DESC_TAG = "select";
    private DicDataTagService dicDataTagService;
    private Logger logger = LogManager.getLogger(this.getClass());
    protected DicDataProcessor(String dialectPrefix,DicDataTagService dicDataTagService) {
        super(TemplateMode.HTML, dialectPrefix, null, false, TEXT_ATTRIBUTE, true, PRECEDENCE, true);
        this.dicDataTagService = dicDataTagService;
    }
    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, String attributeValue, IElementTagStructureHandler structureHandler) {
        if(!DESC_TAG.equals(tag.getElementCompleteName())){
            logger.info(tag.getElementCompleteName() + " is not select tag." );
            return;
        }

        List<DictTagEntity> dictTagEntities = dicDataTagService.queryDicInfoByGroupId(attributeValue);
        if(dictTagEntities == null){
            return;
        }
        StringBuffer out = new StringBuffer();
        for(DictTagEntity item:dictTagEntities){
            out.append(" <option value=\"");
            out.append(item.getDicCode());
            out.append("\" ");
            out.append(">");
            out.append(item.getDictName());
            out.append("</option>");
        }
        structureHandler.setBody(out,false);

    }
}
